package com.bridgetree.jubaocrm.ui.project;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.Contact;
import com.bridgetree.jubaocrm.util.CustomerContactInterface;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;

/**
 *客户联系人
 */
public class XMChildCustomerContactActivity extends Activity {
	private final String TAG ="XMChildCustomerContactActivity";
	private Context mContext;
	private PullToRefreshListView xm_of_lv = null;
	private ListView actualListView1 = null;
	private XMChildCustomerContactAdapter mXMChildCustomerContactAdapter = null;
	private Projects mProjects ;
	private String fangtan = "" ;
	private String user_id =""; 
	private String token ="";
	private List<Contact> contacts ;
	private List<String> initSelected;
	public String conName ="";
	//声明一个集合  
	private final List<Integer> intList = new ArrayList<Integer>(); 

	public static final int Finish_Select=0x00001;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xm_customer_contact);
		mContext=this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		contacts=new ArrayList<Contact>();

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_bi_tv_title=(TextView)findViewById(R.id.xm_bi_tv_title);
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
			fangtan = intent.getExtras().getString("fangtan");
			if(null!=fangtan && fangtan.equals("select")){
				xm_bi_tv_title.setText("选择客户联系人");
			}else{
				xm_bi_tv_title.setText("客户联系人");
			}
		}

		findViewById(R.id.xm_cc_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		Button xm_bj_bt_ok = (Button)findViewById(R.id.xm_bj_bt_ok);
		if(null!=fangtan && fangtan.equals("select")){
			xm_bj_bt_ok.setVisibility(View.VISIBLE);
		}else{
			xm_bj_bt_ok.setVisibility(View.GONE);
		}
		xm_bj_bt_ok.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				List<String> selectedList=mXMChildCustomerContactAdapter.getSelectedList();
				if(selectedList!=null){
					if(selectedList.size() == 0){
						conName="";
					}else if(selectedList.size() == 1){
						conName=selectedList.get(0);
					}else  if(selectedList.size() > 1){
						conName=selectedList.get(0);
						for (int i = 1;i<selectedList.size();i++) {  
							conName = conName+","+ selectedList.get(i);  
						}  
					}
				}
				Intent intent=new Intent();
				intent.putExtra("cons", conName);
				setResult(Finish_Select,intent);
				finish();
			}
		});

		xm_of_lv=(PullToRefreshListView)findViewById(R.id.xm_cc_lv);
		xm_of_lv.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(mXMChildCustomerContactAdapter!=null)
					mXMChildCustomerContactAdapter.notifyDataSetChanged();
				if(xm_of_lv!=null)
					xm_of_lv.onRefreshComplete();
			}
		});

		xm_of_lv.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				//				if(firstVisibleItem+visibleItemCount == totalItemCount){
				//					scrollTopBottom=1;
				//				}else if(firstVisibleItem == 0){
				//					scrollTopBottom=0;
				//				}
			}
		});
		actualListView1 = xm_of_lv.getRefreshableView();
		if(intent.getExtras().getString("cons")!=null){
			String cons=intent.getExtras().getString("cons").trim();
			if(cons.length()>0){
				String[] initArr=cons.split(",");
				if(initArr.length>0){
					initSelected=Arrays.asList(initArr);
				}
			}
		}
		if(mProjects!=null|| !fangtan.equals("")){
			getCustomerContactData();
		}

	}

	private void getCustomerContactData() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			//			String URL = "http://crmsoap.woniuwo.cn/project?project_id="+mProjects.getProject_id() 
			//			+"&user_id="+mProjects.getUser_id()+"&token="+mProjects.getToken()+"&validation="+CRMUserBaseInfo.kValication
			//			+"&part=members";
			String URL = Network.API_DOMAIN+"/project?project_id="+mProjects.getProject_id()
			+"&user_id="+user_id+"&token="+token
			+"&validation="+CRMUserBaseInfo.kValication+"&part=contacts";

			final ProgressDialog progressDialog = ProgressDialog.show(this, "网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {  
						@Override
						public void onResponse(JSONObject response) {
							System.out.println("客户联系人 response="+response);  
							ProgressDialogUtil.dissmis(progressDialog);

							try {
								CustomerContactInterface mCustomerContactInterface = new CustomerContactInterface();
								if (!response.isNull("project")) {
									JSONObject project = new JSONObject(response.getString("project"));
									Projects mProjects = new Projects();
									if (!project.isNull("group_id")) {
										String group_id = project.getString("group_id");
										mProjects.setGroup_id(group_id);
									}
									if (!project.isNull("project_id")) {
										String project_id = project.getString("project_id");
										mProjects.setProject_id(project_id);
									}
									if (!project.isNull("contacts")) {
										org.json.JSONArray jsonArr;
										jsonArr = project.getJSONArray("contacts");
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr.length(); i++) {
												Contact mContact = new Contact();
												JSONObject jsonObj2 = jsonArr.getJSONObject(i);
												if (!jsonObj2.isNull("created_user_id")) {
													String created_user_id = jsonObj2.getString("created_user_id");
													mContact.setCreated_user_id(created_user_id);
												}
												if (!jsonObj2.isNull("weixin")) {
													String weixin = jsonObj2.getString("weixin");
													mContact.setWeixin(weixin);
												}
												if (!jsonObj2.isNull("msn")) {
													String msn = jsonObj2.getString("msn");
													mContact.setMsn(msn);
												}
												if (!jsonObj2.isNull("email")) {
													String email = jsonObj2.getString("email");
													mContact.setEmail(email);
												}
												if (!jsonObj2.isNull("commit")) {
													String commit = jsonObj2.getString("commit");
													mContact.setCommit(commit);
												}
												if (!jsonObj2.isNull("cellphone")) {
													String cellphone = jsonObj2.getString("cellphone");
													mContact.setCellphone(cellphone);
												}
												if (!jsonObj2.isNull("job")) {
													String job = jsonObj2.getString("job");
													mContact.setJob(job);
												}
												if (!jsonObj2.isNull("fixed_phone")) {
													String fixed_phone = jsonObj2.getString("fixed_phone");
													mContact.setFixed_phone(fixed_phone);
												}
												if (!jsonObj2.isNull("fullname")) {
													String fullname = jsonObj2.getString("fullname");
													mContact.setFullname(fullname);
												}
												if (!jsonObj2.isNull("qq")) {
													String qq = jsonObj2.getString("qq");
													mContact.setQq(qq);
												}
												contacts.add(mContact);
											}
										}
										mProjects.setContacts(contacts);
									}
									mCustomerContactInterface.setProject(mProjects);
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														mLoginError.setDesc(desc);
														openDailog("失败提示", desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
											mCustomerContactInterface.setErrors(mLoginError);
										}
									}
								}
								conName="";
								mXMChildCustomerContactAdapter = new XMChildCustomerContactAdapter(XMChildCustomerContactActivity.this,contacts,fangtan);
								actualListView1.setAdapter(mXMChildCustomerContactAdapter);
								if (xm_of_lv != null) {
									xm_of_lv.onRefreshComplete();
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					},
					new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {  
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");  
						}  
					});  
			requestQueue.add(jsonObjectRequest); 
		}
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定",new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}



class XMChildCustomerContactAdapter extends BaseAdapter {
	private Context mContext;
	private List<Contact> DrugstoreDataList = null;
	private LayoutInflater listContainer; // 视图容器
	private String fangtan;
	private String Name ="";
	private List<String> selectedList=new ArrayList<String>();
	public List<String> getSelectedList() {
		return selectedList;
	}

	public void setSelectedList(List<String> selectedList) {
		this.selectedList = selectedList;
	}

	public final class ListItemView { // 自定义控件集合
		public RelativeLayout RelativeLayouts; 
		public TextView xm_12_item_tv; 
		public ImageView xm_12_item_iv; 
		public CheckBox xm_12_item_cb; 
	}

	public XMChildCustomerContactAdapter(Context mContext, List<Contact> list,String fangtan) {
		this.mContext = mContext;
		this.DrugstoreDataList = list;
		this.fangtan = fangtan;
		listContainer = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if(initSelected!=null){
			selectedList.addAll(initSelected);
		}
	}

	@Override
	public int getCount() {
		if (DrugstoreDataList != null) {
			return DrugstoreDataList.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return DrugstoreDataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ListItemView listItemView = null;
		convertView = null;
		listItemView = new ListItemView();
		// 获取list_item布局文件的视图
		convertView = listContainer.inflate(R.layout.xm_12_item, null);
		// 获取控件对象
		listItemView.RelativeLayouts = (RelativeLayout) convertView.findViewById(R.id.RelativeLayouts);
		listItemView.xm_12_item_tv = (TextView) convertView.findViewById(R.id.xm_12_item_tv);
		listItemView.xm_12_item_iv = (ImageView) convertView.findViewById(R.id.xm_12_item_iv);
		listItemView.xm_12_item_cb = (CheckBox) convertView.findViewById(R.id.xm_12_item_cb);
		// 设置控件集到convertView
		convertView.setTag(listItemView);
	
		final String name = DrugstoreDataList.get(position).getFullname();
		listItemView.xm_12_item_tv.setText(name);
		
		if(null!=fangtan && fangtan.equals("select")){
			if(selectedList!=null && selectedList.contains(name)){
				listItemView.xm_12_item_cb.setChecked(true);
			}
			listItemView.xm_12_item_cb.setVisibility(View.VISIBLE);
			listItemView.xm_12_item_iv.setVisibility(View.GONE);
			//			checkBoxs.add(listItemView.xm_12_item_cb); 
			listItemView.xm_12_item_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {  
				@Override  
				public void onCheckedChanged(CompoundButton buttonView,  
						boolean isChecked) {  
					// TODO Auto-generated method stub  
					//					CheckBox box = (CheckBox) buttonView;  
					if(isChecked){
						selectedList.add(DrugstoreDataList.get(position).getFullname());
					}else{
						selectedList.remove(DrugstoreDataList.get(position).getFullname());
					}

					//					Toast.makeText(mContext,  
					//							"获取的值:" + isChecked + "xxxxx" + (String) DrugstoreDataList.get(position).getFullname() ,  
					//							Toast.LENGTH_LONG).show();  
					//					if(XMChildAddEgressActivity.conName.equals("")){
					//						XMChildAddEgressActivity.conName = (String) DrugstoreDataList.get(position).getFullname();
					//					}else{
					//						XMChildAddEgressActivity.conName =XMChildAddEgressActivity.conName +","+ (String) DrugstoreDataList.get(position).getFullname();
					//					}
				}  
			});  
		}else{
			listItemView.xm_12_item_cb.setVisibility(View.GONE);
			listItemView.xm_12_item_iv.setVisibility(View.VISIBLE);
			listItemView.RelativeLayouts .setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent=null;
					Bundle bundle=null;
					intent = new Intent(mContext, XMChildCustomerContactItemActivity.class);
					bundle = new Bundle();
					bundle.putSerializable("Contact", DrugstoreDataList.get(position));
					intent.putExtras(bundle);
					mContext.startActivity(intent);
				}
			});
		}
		//		listItemView.xm_12_item_iv.setVisibility(View.GONE);



		return convertView;
	}


}
}
